package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.config.player.DecorationInfo;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.eDecorationType;
import com.yanqu.road.entity.enums.eSexType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.redis.RedisKeyDefineHelper;
import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.server.helper.PlatformHttpHelper;
import com.yanqu.road.server.manger.DecorationMgr;
import com.yanqu.road.server.manger.NameMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseGameHttpServlet;
import com.yanqu.road.web.mgr.UserIdMgr;
import com.yanqu.road.web.util.IpAddressHelper;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/createRole")
public class WebCreateRole extends BaseGameHttpServlet {

    private Logger logger = LogManager.getLogger(WebCreateRole.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpGameWebParam httpGameWebParam = super.parseRequest(request);
        createRole(request, response, httpGameWebParam);
    }

    private void createRole(HttpServletRequest request, HttpServletResponse response, HttpGameWebParam httpGameWebParam) {
        JSONObject paramObj = httpGameWebParam.getParamObj();
        String param = httpGameWebParam.getParam();
        String language = httpGameWebParam.getLanguage();

        short sex;
        int headId;
        String nickName;
        long userId;
        //服饰id
        int costumeId;
        String appId = "";
        String appExt = "";

        boolean isPreCreate = false;

        try{
            userId = paramObj.getLong("userId");
            sex = paramObj.getShort("sex");
            headId = paramObj.getInteger("headId");
            costumeId = paramObj.getInteger("costumeId");
            nickName = StringUtils.autoToUtf8(paramObj.getString("nickName"));
            appId = paramObj.getString("appId");
            appExt = paramObj.getString("appExt");

            nickName = StringUtils.clearHeadAndTailEmpty(nickName);

            if(paramObj.containsKey("isPreCreate")){
                isPreCreate = paramObj.getBoolean("isPreCreate");
            }


            //增加空白名字判断
            String checkName = StringUtils.clearBlankSpace(nickName);
            if(StringUtils.isNullOrEmpty(checkName)){
                sendMessage(response, getResultObj(GameErrorCode.E_FORBIDDEN_WORD, language).toJSONString());
                return;
            }


            if(userId == 0){
                sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                return;
            }
            if(StringUtils.isNullOrEmpty(nickName)){
                sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                return;
            }
            if(headId == 0){
                sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                return;
            }
            if(costumeId == 0){
                sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                return;
            }
            if(eSexType.parse(sex) == null){
                sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
                return;
            }
        } catch (Exception e) {
            logger.error("queryPlayerOnline args error:" + e);
            sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
            return;
        }
        UserInfo userInfo = null;
        if(isPreCreate){
            userInfo = UserBussiness.getUserInfoPreByUserId(userId);
        }else{
            userInfo = UserBussiness.getUserInfoByUserId(userId);
        }
        if(null == userInfo){
            sendMessage(response, getResultObj(GameErrorCode.E_USER_NO_FOUND, language).toJSONString());
            return;
        }
        if (!StringUtils.isNullOrEmpty(userInfo.getNickName())){
            sendMessage(response, getResultObj(GameErrorCode.E_ROLE_ALREADY_EXIST, language).toJSONString());
            return;
        }
        if (UserBussiness.isSameNickName(nickName)) {
            sendMessage(response, getResultObj(GameErrorCode.E_NICK_NAME_SAME, language).toJSONString());
            return;
        }
        int nameLength = StringUtils.getStringLen(nickName);
        int channelId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
        if(nameLength > NameMgr.getMaxNickNameLength(channelId) || nameLength < NameMgr.MIN_NICK_NAME_LENGTH){
            sendMessage(response, getResultObj(GameErrorCode.E_NAME_LENGTH_OVER, language).toJSONString());
            return;
        }
        //敏感字过滤
        if(GameWebServiceInvoke.checkNameForbidden(nickName)){
            sendMessage(response, getResultObj(GameErrorCode.E_FORBIDDEN_WORD, language).toJSONString());
            return;
        }
        if(eChannelType.isMainLandChannel(channelId)
                && ChannelConfig.CN_FORBIDDEN_WORD_CHECK == 1
//                && channelId != eChannelType.Mobile_ZFB.getValue()
        ){//大陆渠道，敏感词过滤
            long curTime = System.currentTimeMillis();
            boolean isForbidden = PlatformHttpHelper.platformCheckNickName(WebServer.getInstance().getServerId(), userInfo.getPlatformUserId(), userId,
                    nickName, IpAddressHelper.getIpAddr(request), appId, appExt);
            logger.info("platformCheckNickName use:{}ms", System.currentTimeMillis() - curTime);
            if(isForbidden){
                sendMessage(response, getResultObj(GameErrorCode.E_FORBIDDEN_WORD, language).toJSONString());
                return;
            }
        }
        DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(headId);
        if (decorationInfo == null) {
            decorationInfo = DecorationMgr.getDefaultDecoration(eDecorationType.HeadIcon.getValue(), sex);
            if (decorationInfo == null) {
                sendMessage(response, getResultObj(GameErrorCode.E_HEAD_ICON_NO_FOUND, language).toJSONString());
                return;
            }
            headId = decorationInfo.getId();
        }
        if (decorationInfo.getSex() != sex) {
            sendMessage(response, getResultObj(GameErrorCode.E_HEAD_ICON_NO_FOUND, language).toJSONString());
            return;
        }
        if (!decorationInfo.isFree()) {
            sendMessage(response, getResultObj(GameErrorCode.E_HEAD_ICON_NO_FOUND, language).toJSONString());
            return;
        }
        decorationInfo = DecorationMgr.getDecorationInfo(costumeId);
        if (decorationInfo == null) {
            decorationInfo = DecorationMgr.getDefaultDecoration(eDecorationType.Costume.getValue(), sex);
            if (decorationInfo == null) {
                sendMessage(response, getResultObj(GameErrorCode.E_COSTUME_NO_FOUND, language).toJSONString());
                return;
            }
            costumeId = decorationInfo.getId();
        }
        if (decorationInfo.getSex() != sex) {
            sendMessage(response, getResultObj(GameErrorCode.E_COSTUME_NO_FOUND, language).toJSONString());
            return;
        }
        if (!decorationInfo.isFree()) {
            sendMessage(response, getResultObj(GameErrorCode.E_COSTUME_NO_FOUND, language).toJSONString());
            return;
        }
        String decoration = DecorationMgr.webFullDefaultDecoration(headId, costumeId, sex);
        boolean success = false;
        if(isPreCreate){
            if (ServerListMgr.isRegisterPreCountMax(WebServer.getInstance().getServerId())) {
                sendMessage(response, getResultObj(GameErrorCode.E_REGISTER_PRE_SERVER_MAX, language).toJSONString());
                return;
            }
            success = UserBussiness.updatePreUserRoleInfo(userId, sex, nickName, decoration);
            if(success){
                try{
                    long serverId = WebServer.getInstance().getServerId();
                    RedisManger.getRedisUtil().zadd("PLAYERFISHSERVER"+ "_" + userInfo.getOpenId(),System.currentTimeMillis()/1000,serverId+"");
                    //设置key半年失效
                    RedisManger.getRedisUtil().expire("PLAYERFISHSERVER"+ "_" + userInfo.getOpenId(),60*60*24*30*6);
                }catch (Exception e){
                    logger.error("addToRegisterFishServerList error", e);
                }
//                UserBussiness.updatePreServer(nickName, userId);
                ServerListMgr.addRegisterPreCount(WebServer.getInstance().getServerId());
            }
        }else{
            success = UserBussiness.updateUserRoleInfo(userId, sex, nickName, decoration);
        }
        if (success) {
            sendMessage(response, getResultObj(0, language).toJSONString());
            //增加创角数
            UserIdMgr.addRoleCreateCount(1);
            //增加了实时昵称检测，不用上报了
            //创角埋点使用，不能注释
            GameWebServiceInvoke.roleReport(userInfo.getOpenId(), String.valueOf(userId), nickName, IpAddressHelper.getIpAddr(request));
        } else {
            sendMessage(response, getResultObj(GameErrorCode.E_ROLE_CREATE_ERROR, language).toJSONString());
        }
    }
}
